package com.raquel.privateservlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author Raquel Valenzuela
 * Servlet implementation class Private
 * <if login is correct, redirects to private.jsp
 * 
 */
@WebServlet("/Private")
public class Private extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Private() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * Checks login
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		checkSession(request, response);
		
	}
	
	/**
	 * Checks login
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		checkSession(request, response);
	}
	
	/**
	 * Checks if login attribute is not null
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void checkSession(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		HttpSession session=request.getSession();
		
		//is session started?
		if (null != session.getAttribute("login")){
			this.getServletContext().getRequestDispatcher("/private.jsp").forward(request, response);
			
		} else{
			this.getServletContext().getRequestDispatcher("/SignIn").forward(request, response);
		}
	}

}
